//
//  WZUpdateController.m
//  ETong
//
//  Created by wanzhao on 15/10/30.
//  Copyright (c) 2015年 wanzhao. All rights reserved.
//

#import "WZUpdateController.h"
#import "MBProgressHUD+WZ.h"
#import "NetWorkShare.h"

@interface WZUpdateController ()

@property (nonatomic, weak) UIButton *versionBtn;
@property (nonatomic, weak) UITextView *introLabel;
@property (nonatomic, copy) NSString *updateUrl;

@end

@implementation WZUpdateController

- (void)dealloc
{
    NSLog(@"WZUpdateController dealloc");
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = RGBCOLORWITH16COLOR(0xeeeeee);
    
    //版本介绍按钮
    UIButton *versionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [versionButton setImage:[UIImage imageNamed:@"logo_helper"] forState:UIControlStateNormal];
    versionButton.backgroundColor = ClearColor;
    versionButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    versionButton.imageEdgeInsets = UIEdgeInsetsMake(0, OppositeWidthRate(20), 0, 0);
    versionButton.titleEdgeInsets = UIEdgeInsetsMake(0, OppositeWidthRate(40), 0, 0);
    versionButton.userInteractionEnabled = NO;
    [versionButton setTitleColor:RGBCOLORWITH16COLOR(0x333333) forState:UIControlStateNormal];
    versionButton.titleLabel.font = Font15;
    versionButton.titleLabel.numberOfLines = 0;
    versionButton.frame = CGRectMake(0, 0, self.view.width, OppositeHeightRate(100));
    [self.view addSubview:versionButton];
    self.versionBtn = versionButton;
    
    UIView *introView = [[UIView alloc] init];
    introView.backgroundColor = WhiteColor;
    [self.view addSubview:introView];
    
    UITextView *vesionIntroduce = [[UITextView alloc] init];
    vesionIntroduce.font = Font15;
    vesionIntroduce.userInteractionEnabled = NO;
    vesionIntroduce.textColor = RGBCOLORWITH16COLOR(0x333333);
    vesionIntroduce.backgroundColor = ClearColor;
    vesionIntroduce.textAlignment = NSTextAlignmentLeft;
    
//    CGSize textSize = [vesionIntroduce.text sizeWithFont:vesionIntroduce.font maxSize:CGSizeMake(self.view.width - OppositeWidthRate(40), OppositeHeightRate(160))];
    vesionIntroduce.frame = vesionIntroduce.frame = CGRectMake(OppositeWidthRate(20), OppositeHeightRate(10), self.view.width - OppositeWidthRate(40), OppositeHeightRate(160));
    [introView addSubview:vesionIntroduce];
    self.introLabel = vesionIntroduce;
    
    //计算introview的frame
    introView.frame = CGRectMake(0, CGRectGetMaxY(versionButton.frame), self.view.width, CGRectGetMaxY(vesionIntroduce.frame) + OppositeHeightRate(20));
    
    //下载按钮
    UIButton *footButton = [UIButton buttonWithType:UIButtonTypeCustom];
    footButton.backgroundColor = WhiteColor;
    footButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    footButton.titleEdgeInsets = UIEdgeInsetsMake(0, OppositeWidthRate(20), 0, 0);
    footButton.userInteractionEnabled = YES;
    [footButton setTitle:[NSString stringWithFormat:@"下载并安装"] forState:UIControlStateNormal];
    [footButton setTitleColor:RGBCOLORWITH16COLOR(0x333333) forState:UIControlStateNormal];
    footButton.titleLabel.font = Font18;
    footButton.titleLabel.numberOfLines = 0;
    [footButton addTarget:self action:@selector(downloadNewVersion) forControlEvents:UIControlEventTouchUpInside];
    footButton.frame = CGRectMake(0, CGRectGetMaxY(introView.frame) + OppositeHeightRate(20), self.view.width, OppositeHeightRate(55));
    [self.view addSubview:footButton];
    
    
    NSString *key = (__bridge_transfer NSString *)kCFBundleVersionKey;
    NSDictionary *dict = [NSBundle mainBundle].infoDictionary;
    NSString *currentVersion = dict[key];

    [self updateVersionWithCurVersion:currentVersion];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}


- (void)updateVersionWithCurVersion:(NSString *)curVersion
{
    
    __block typeof(self) weakSelf = self;
    [MBProgressHUD showMessage:nil toView:self.view];
    [NetWorkShare getNewVersionWithCurrentVersion:curVersion successHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        if (responseObject) {
           
            if ([[responseObject objectForKey:@"success"] boolValue]) {
                if ([[responseObject objectForKey:@"newflage"] boolValue]) {
                    NSDictionary *desDict = [responseObject objectForKey:@"versionInfo"];
                    [weakSelf.versionBtn setTitle:[NSString stringWithFormat:@"e同办公%@\n%@M",[desDict objectForKey:@"version"],[desDict objectForKey:@"size"]] forState:UIControlStateNormal];
                    weakSelf.introLabel.text = [desDict objectForKey:@"describe"];
                    weakSelf.updateUrl = [desDict objectForKey:@"url"];
                    
                } else {
                    NSString *key = (__bridge_transfer NSString *)kCFBundleVersionKey;
                    NSDictionary *dict = [NSBundle mainBundle].infoDictionary;
                    NSString *currentVersion = dict[key];

                    [weakSelf.versionBtn setTitle:[NSString stringWithFormat:@"e同办公V%@",currentVersion] forState:UIControlStateNormal];
                    weakSelf.introLabel.text = [responseObject objectForKey:@"message"];
                }
                
            } else {
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
            
        } else {
            [MBProgressHUD showError:@"未知错误"];
        }

      
    } failureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"网络错误"];
    }];
}


- (void)downloadNewVersion
{
//    self.updateUrl = @"itms-services://?action=download-manifest&url=https://kaifa.wanzhao.com/iOS/WZ_Etong.plist";
    if (M_ISSTRNULL(self.updateUrl)) {
        
        [MBProgressHUD showError:@"没有可供更新的新版本"];
        return;
    }
    
    
    UIApplication *app = [UIApplication sharedApplication];
    NSURL *url = [NSURL URLWithString:[self.updateUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    if ([app canOpenURL:url]) {
        [app openURL:url];
    }
}

@end
